package com.mojo.quartz;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Timer实现定时任务
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/10 17:04
 */
@Slf4j
public class TimerDemo {
    @SneakyThrows
    public static void timer() {
        // start timer
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                log.info("timer-task @{}", LocalDateTime.now());
            }
        }, 1000);

        // waiting to process(sleep to mock)
        Thread.sleep(3000);

        // stop timer
        timer.cancel();
    }

    @SneakyThrows
    public static void timerPeriod() {
        // start t
        Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            @SneakyThrows
            public void run() {
                log.info("t-period-task @{}", LocalDateTime.now());
                log.info(">>>timerPeriod>>线程名称:{}", Thread.currentThread().getName());
                Thread.sleep(100);
                // 可以设置的执行时间, 来测试当执行时间大于执行周期时任务执行的变化
            }
        }, 500, 1000);

        // waiting to process(sleep to mock)
        Thread.sleep(10000);

        // stop t
        t.cancel();
    }

    @SneakyThrows
    public static void timerFixedRate() {
        // start timer
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            int count = 0;

            @SneakyThrows
            public void run() {
                if (count++ == 2) {
                    Thread.sleep(5000); // 某一次执行时间超过了period(执行周期）
                }
                log.info("timer-fixedRate-task @{}", LocalDateTime.now());
                log.info(">>>timerFixedRate>>线程名称:{}", Thread.currentThread().getName());

            }
        }, 500, 1000);

        // waiting to process(sleep to mock)
        Thread.sleep(10000);

        // stop timer
        timer.cancel();
    }


    public static void main(String[] args) {
        //timer();
        timerPeriod();
        timerFixedRate();
    }

}
